package GradeManager.StudentGradeSystem.filter;

import GradeManager.StudentGradeSystem.common.BaseContent;
import GradeManager.StudentGradeSystem.pojo.LoginDTO;
import GradeManager.StudentGradeSystem.pojo.Result;
import GradeManager.StudentGradeSystem.utils.JwtUtils;
import GradeManager.StudentGradeSystem.utils.MessageUtils;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

@Slf4j
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    private static Claims claims;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        resp.setHeader(  "Access-Control-Allow-Origin","*");//允许所有来源访问
        resp.setHeader(  "Access-Control-Allow-Methods","*");//允许所有方法访问
        resp.setHeader(  "Access-Control-Allow-Credentials","true");//允许访问的方式
        resp.setHeader(  "Access-Control-Allow-Headers","*");//允许携带请求头


        resp.setContentType("application/json;charset=utf-8");
//        获取当前请求路径
        String requestURI = req.getRequestURI();
        log.info("当前访问的路径:{}",requestURI);
//        需要放行的路径
        String[] urls=new String[]{
                "/accounts/check/*",
                "/accounts/login",
                "/accounts/register",
                "/addInfo/upload",
                "/addInfo/download"
        };
        for(String url:urls){
            if(PATH_MATCHER.match(url,requestURI)){
//                如果路径匹配成功则放行
                filterChain.doFilter(req,resp);
                return;
            }
        }
//        判断是否登录
        String token = req.getHeader("authorization");
        log.info("jwt令牌：{}",token);
        if("null".equals(token) || token==null){
            log.info("未登录！！");
            resp.getWriter().write(JSON.toJSONString(Result.error(MessageUtils.NOT_LOGIN)));
            return;
        }
//        判断登录是否有效
        try{
            claims = jwtUtils.JwtParser(token);
        }catch (Exception e){
            //登录无效，记录日志并返回给前端
            e.printStackTrace();
            log.info("登录失效！请重新登录！");
            resp.getWriter().write(JSON.toJSONString(Result.error(MessageUtils.NOT_LOGIN)));
            return;
        }
        //有效则放行
        log.info("登录的账号信息：{}",claims);
        BaseContent.setLoginClaims(claims);
        filterChain.doFilter(req,resp);
    }
}
